package net.easyjava.third.rongcloud;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.easyjava.third.rongcloud.exception.RongCloudException;
import net.easyjava.third.rongcloud.rong.ApiHttpClient;
import net.easyjava.third.rongcloud.rong.constants.RongCloudConstants;
import net.easyjava.third.rongcloud.rong.models.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException ;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by wxnacy on 16/1/7.
 */
public class RongCloudClient {
    private Logger logger = LoggerFactory.getLogger(RongCloudClient.class);
    
    private String appKey;
    private String appSecret;
    
    /**
     * 构造单例
     */
    private volatile static RongCloudClient singleton;
    private RongCloudClient(final String appKey,final String appSecret){
        this.appKey = appKey;
        this.appSecret = appSecret;
    }
    public static RongCloudClient getInstance(final String appKey,final String appSecret) {
        if (singleton == null) {
            synchronized (RongCloudClient.class) {
                if (singleton == null) {
                    singleton = new RongCloudClient(appKey, appSecret);
                }
            }
        }
        return singleton;
    }

    /**
     * 获取token
     * @param userId
     * @param userName
     * @param faceUrl
     * @return
     */
    public String getToken(String userId,String userName,String faceUrl) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.getToken(this.appKey, this.appSecret, userId, userName, faceUrl);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        UserToken userInfo = JSONObject.parseObject(sdkHttpResult.getResult(),UserToken.class);
        return userInfo.getToken();
    }





    /**
     * 创建聊天室
     * @param chatroomId
     * @param name
     * @return
     */
    public boolean createChatroom(String chatroomId,String name) throws IOException , RongCloudException {
        ChatroomInfo chatroomInfo = new ChatroomInfo(chatroomId,name);
        List<ChatroomInfo> list = Arrays.asList(chatroomInfo);
        SdkHttpResult sdkHttpResult = ApiHttpClient.createChatroom(this.appKey, this.appSecret, list);

        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }
    public boolean createChatroom(List<ChatroomInfo> list) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.createChatroom(this.appKey, this.appSecret, list);

        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }
    /**
     * 查找一个聊天室的信息
     * @param chatroomId
     * @return
     */
    public ChatroomInfo getChatroom(String chatroomId) throws IOException, RongCloudException {
        List<String> chatIds = Arrays.asList(chatroomId);
        List<ChatroomInfo> chatroomInfos = getChatrooms(chatIds);
        if(chatroomInfos.size()>0){
            return chatroomInfos.get(0);
        }
        return null;
    }
    public List<ChatroomInfo> getChatrooms(List<String> chatroomIds) throws IOException, RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.queryChatroom(this.appKey, this.appSecret, chatroomIds);
//        System.out.println("sdkHttpResult = " + sdkHttpResult);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        List<ChatroomInfo> chatroomInfos = JSONArray.parseArray(sdkHttpResult.getResultJson().getJSONArray("chatRooms").toJSONString(),ChatroomInfo.class);
        return chatroomInfos;
    }


    /**
     * 加入聊天室
     * @param chatroomId
     * @param uids
     * @return
     * @throws IOException , RongCloudException
     */
    public boolean joinChatroom(String chatroomId,List<String> uids) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.joinChatroom(this.appKey, this.appSecret, uids, chatroomId);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }
    public List<UserInfo> getChatroomUsers(String chatroomId) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.queryChatroomUsers(this.appKey, this.appSecret, chatroomId);
        List<UserInfo> userInfos = JSONArray.parseArray(sdkHttpResult.getResultJson().getJSONArray("users").toJSONString(), UserInfo.class);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return userInfos;
    }


    /**
     * 向聊天内发送消息
     * @param chatroomId
     * @param fromUserId
     * @param content
     * @return
     */
    public boolean sendChatroomMessage(String fromUserId,String chatroomId,String content) throws IOException , RongCloudException {
        return sendChatroomMessage(fromUserId, Arrays.asList(chatroomId), content);
    }
    public boolean sendChatroomMessage(String fromUserId,List<String> chatroomIds,String content) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.publishChatroomMessage(this.appKey, this.appSecret, fromUserId, chatroomIds, new TxtMessage(content));
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }
    public boolean sendChatroomMessage(String fromUserId,String chatroomId,Message message) throws IOException , RongCloudException {
        return sendChatroomMessage(fromUserId, Arrays.asList(chatroomId), message);
    }
    public boolean sendChatroomMessage(String fromUserId,List<String> chatroomIds,Message message) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.publishChatroomMessage(this.appKey, this.appSecret, fromUserId, chatroomIds, message);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }
    public boolean sendBroadcastMessage(String fromUserId,Message message,String os) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.publishBroadcastMessage(this.appKey, this.appSecret, fromUserId, message, os);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }
    public boolean sendBroadcastMessage(String fromUserId,Message message) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.publishBroadcastMessage(this.appKey, this.appSecret, fromUserId, message, null);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }
    public boolean sendBroadcastMessage(String fromUserId,String content) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.publishBroadcastMessage(this.appKey, this.appSecret, fromUserId, new TxtMessage(content), null);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }


    /**
     * 发送系统消息
     * @param fromUserId
     * @param userIds
     * @param content
     * @param pushContent
     * @return
     * @throws IOException
     * @throws RongCloudException
     */
    public boolean sendSystemMessage(String fromUserId,List<String> userIds,String content,String pushContent) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.publishSystemMessage(this.appKey, this.appSecret, fromUserId, userIds, new TxtMessage(content), pushContent, null, FormatType.json);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }
    public boolean sendSystemMessage(String fromUserId,List<String> userIds,Message message,String pushContent) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.publishSystemMessage(this.appKey, this.appSecret, fromUserId, userIds, message, pushContent, null, FormatType.json);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }


    /**
     * 所有人广播推送
     * @param fromUserId
     * @param alert
     * @param message
     * @return
     * @throws IOException
     * @throws RongCloudException
     */
    public boolean sendBroadcastPushToAll(String fromUserId,String alert,Message message) throws IOException , RongCloudException {
        return sendBroadcastPushMessage(fromUserId, alert, message, RongCloudConstants.PushType.ALL, true, null,null);
    }
    public boolean sendBroadcastPushToIOS(String fromUserId,String alert,Message message) throws IOException , RongCloudException {
        return sendBroadcastPushMessage(fromUserId, alert, message, RongCloudConstants.PushType.IOS, true, null,null);
    }
    public boolean sendBroadcastPushToAndroid(String fromUserId,String alert,Message message) throws IOException , RongCloudException {
        return sendBroadcastPushMessage(fromUserId, alert, message, RongCloudConstants.PushType.ANDROID, true, null,null);
    }
    public boolean sendBroadcastPushToTags(String fromUserId,String alert,Message message,String... tags) throws IOException , RongCloudException {
        return sendBroadcastPushMessage(fromUserId, alert, message, RongCloudConstants.PushType.ALL, false, Arrays.asList(tags),null);
    }


    /**
     * 广播推送
     * @param fromUserId 发送人id
     * @param alert 提示内容
     * @param message 内容
     * @param pushType 推送类型 all ios android
     * @param isToAll 是否推给全部人
     * @param tags 推送标签的人
     * @param userIds 推送的人
     * @return
     * @throws IOException
     * @throws RongCloudException
     */
    public boolean sendBroadcastPushMessage(String fromUserId,String alert,Message message,RongCloudConstants.PushType pushType,
                                   boolean isToAll,List<String> tags,List<String> userIds) throws IOException , RongCloudException {

        PushMessage pushMessage = new PushMessage(fromUserId);

        pushMessage.setPlatform(pushType.getList());

        /**推送对象*/
        TagObj tagObj = new TagObj();
        tagObj.setIs_to_all(isToAll);
        if(tags != null && tags.size()>0){
            tagObj.setTag(tags);
        }
        if(userIds != null && userIds.size()>0){
            tagObj.setUserid(userIds);
        }

        pushMessage.setAudience(tagObj);

        /**消息内容*/
        MsgObj msg = new MsgObj();
        msg.setContent(message.toString());
        msg.setObjectName(message.getType());

        pushMessage.setMessage(msg);

        /**推送标题*/
        PushNotification notification = new PushNotification(alert);
        pushMessage.setNotification(notification);
        System.out.println("pushMessage = " + pushMessage.toJsonString());


//        String data = "{\"platform\":[\"ios\",\"android\"],\"fromuserid\": \"1\",\"audience\":{\"is_to_all\":true},\"message\": {\"content\": \"{\\\"content\\\":\\\"1111\\\",\\\"extra\\\":\\\"aa\\\"}\",\"objectName\": \"RC:TxtMsg\"},\"notification\":{\"alert\":\"this is a push\",\"ios\": {\"alert\": \"iOS 通知显示内容\",\"extras\": {\"id\": \"1\",\"name\": \"2\"}},\"android\": {\"alert\": \"Android 通知显示内容\",\"extras\": {\"id\": \"1\",\"name\": \"2\"}}}}";
//
//        JSONObject send = JSONObject.parseObject(data);
//        System.out.println("send = " + send);
        SdkHttpResult sdkHttpResult = ApiHttpClient.publishBroadcastPushMessage(this.appKey, this.appSecret, pushMessage.toJsonString());
        System.out.println("sdkHttpResult.toJsonString() = " + sdkHttpResult.toJsonString());
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }

    /**
     * 设置标签
     * @param userId
     * @param tags
     * @return
     * @throws IOException
     * @throws RongCloudException
     */
    public boolean setTags(String userId,String... tags) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.setTags(this.appKey, this.appSecret, userId,tags);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }







    /**
     * 发送单聊
     * @param fromUserId
     * @param toUserId
     * @param content
     * @return
     * @throws IOException , RongCloudException
     */
    public boolean sendPrivateMessage(String fromUserId,String toUserId,String content) throws IOException , RongCloudException {
        return sendPrivateMessage(fromUserId, Arrays.asList(toUserId), content);
    }
    public boolean sendPrivateMessage(String fromUserId,List<String> toUserIds,String content) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.publishMessage(this.appKey, this.appSecret, fromUserId, toUserIds, new TxtMessage(content), FormatType.json);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }


    /**
     * 拉黑用户
     * @param userId
     * @param blackUser
     * @return
     * @throws IOException , RongCloudException
     */
    public boolean blackUser(String userId,String blackUser) throws IOException , RongCloudException {
        return blackUser(userId, Arrays.asList(blackUser));
    }
    public boolean blackUser(String userId,List<String> blackUsers) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.blackUser(this.appKey, this.appSecret, userId, blackUsers, FormatType.json);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }

    /**
     * 移除拉黑用户
     * @param userId
     * @param blackUser
     * @return
     * @throws IOException , RongCloudException
     */
    public boolean removeBlackUser(String userId,String blackUser) throws IOException , RongCloudException {
        return removeBlackUser(userId, Arrays.asList(blackUser));
    }
    public boolean removeBlackUser(String userId,List<String> blackUsers) throws IOException , RongCloudException {
        SdkHttpResult sdkHttpResult = ApiHttpClient.unblackUser(this.appKey, this.appSecret, userId, blackUsers, FormatType.json);
        if(sdkHttpResult.isError()){
            throw new RongCloudException(sdkHttpResult.getResult());
        }
        return true;
    }

    /**
     * 获取拉黑用户列表
     * @param userId
     * @return
     * @throws Exception
     */
    public List<String> getBlackUids(String userId) throws Exception {
        SdkHttpResult sdkHttpResult = ApiHttpClient.QueryblackUser(this.appKey, this.appSecret, userId, FormatType.json);
        if(sdkHttpResult.isError()){
            return new ArrayList<>();
        }

        JSONObject jsonObject = JSONObject.parseObject(sdkHttpResult.getResult());
        List<String> list = JSONObject.parseArray(jsonObject.getJSONArray("users").toJSONString(), String.class);
        return list;
    }


    /**
     * 封禁用户
     * @param userId
     * @param minute 封禁时长,单位为分钟，最大值为43200分钟
     * @return
     * @throws Exception
     */
    public boolean blockUser(String userId,int minute) throws Exception {
        SdkHttpResult sdkHttpResult = ApiHttpClient.blockUser(this.appKey, this.appSecret, userId, minute, FormatType.json);
        if(sdkHttpResult.isError()){
            return false;
        }

        return true;
    }


    /**
     * 解禁用户
     * @param userId
     * @return
     * @throws Exception
     */
    public boolean unBlockUser(String userId) throws Exception {
        SdkHttpResult sdkHttpResult = ApiHttpClient.unblockUser(this.appKey, this.appSecret, userId, FormatType.json);
        if(sdkHttpResult.isError()){
            return false;
        }

        return true;
    }










    public static void main(String[] args) {
    }
}
